'use strict';

import * as monent from 'moment'

class ChargeDao {
    handle: any
    constructor(db) {
        this.handle = db.collection("charge")
        this.handle.createIndex("orderID", 1)
        this.handle.createIndex("pID", 1)
        this.handle.createIndex("time", -1)
        this.handle.createIndex({day: 1,  isPay: 1 })
    }

    newAndSave = async (orderID,  pID, amount, productID): Promise<any> => {
        let date = new Date().getTime()
        return await this.handle.insertOne({
            orderID: orderID,
            pID: pID,
            amount: amount, //需要支付的金钱
            productID: productID, //购买产品
            isPay: false, //是否支付
            time: date,
            day: monent().startOf('day').valueOf(),
        });
    }

    findOne = async (query): Promise<any> => {
        return await this.handle.findOne(query)
    }

    find = async (query): Promise<any[]> => {
        return await this.handle.find(query).toArray()
    }

    findAndSort = async (query, sort) => {
        return await this.handle.find(query).sort(sort).toArray();
    };

    findByPage = async (query, start: number, size: number): Promise<any[]> => {
        return await this.handle.find(query).skip(start).limit(size).toArray()
    }

    findByPageAndSort = async (query, sort, start, size): Promise<any[]> => {
        return await this.handle.find(query).sort(sort).skip(start).limit(size).toArray()
    }

    updateMany = async (query, data): Promise<any> => {
        return await this.handle.updateMany(query, data);
    }

    updateOne = async (query, data): Promise<any> => {
        return await this.handle.updateOne(query, data);
    }

    count = async (query): Promise<number> => {
        return await this.handle.countDocuments(query)
    }

    remove = async (query): Promise<any> => {
        return await this.handle.remove(query, {
            multi: true
        });
    }
}

export default ChargeDao